import base64 from "./base64"
import md5 from "./md5"
import sha1 from "./sha1"

// 生成参数字符串
function genParamsString(params = {}) {
  const keys = Object.keys(params).sort()
  return keys.map((key) => `${key}${params[key]}`).join("")
}

function utf16to8(str) {
  let out, i, len, c
  out = ""
  len = str.length
  for (i = 0; i < len; i++) {
    c = str.charCodeAt(i)
    if (c >= 0x0001 && c <= 0x007f) {
      out += str.charAt(i)
    } else if (c > 0x07ff) {
      out += String.fromCharCode(0xe0 | ((c >> 12) & 0x0f))
      out += String.fromCharCode(0x80 | ((c >> 6) & 0x3f))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f))
    } else {
      out += String.fromCharCode(0xc0 | ((c >> 6) & 0x1f))
      out += String.fromCharCode(0x80 | ((c >> 0) & 0x3f))
    }
  }
  return out
}

// 编码ext
export function encodeExt(data = "", method = "post") {
  let str = String(base64.encode(JSON.stringify(data)))
  if (method === "get") {
    str = str.replace(/\+/g, "{A}")
    str = str.replace(/\//g, "{S}")
  }
  str = str.replace(/=/g, "{Q}")
  return str
}

// 编码表单信息
export function encodeVerifyInfo(params, pws) {
  let str = genParamsString(params) + pws
  let sha1Str = sha1(utf16to8(str))
  let md5Str = md5(sha1Str)
  return md5Str.toLowerCase().substring(8, 24)
}

// 解码pwy
export function decodePwy(pwy = "") {
  let s = pwy.replace(/zmgang/g, "/")
  s = s.replace(/zmqe/g, "=")
  s = s.replace(/zmque/g, "?")
  s = s.replace(/zmand/g, "&")
  return s
}

// 加密Pwy
export const encodePwy = (str) => {
  let s = str.replace(/\//g, "zmgang")
  s = s.replace(/=/g, "zmqe")
  s = s.replace(/\?/g, "zmque")
  s = s.replace(/&/g, "zmand")
  return s
}
